// 第三方库 JavaScript 文件
// 使用 script 标签方式加载，确保全局变量正确暴露

// 创建并添加 script 标签来加载库文件
function loadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = src;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

// 按依赖顺序加载（jQuery 现在在 HTML 中先加载）
async function loadVendorLibs() {
  try {
    // 等待 jQuery 加载完成（从 HTML 中加载）
    if (typeof window.jQuery === 'undefined') {
      console.log('等待 jQuery 从 HTML 加载...');
      await new Promise((resolve) => {
        const checkJQuery = () => {
          if (typeof window.jQuery !== 'undefined') {
            console.log('jQuery 已从 HTML 加载完成');
            resolve();
          } else {
            setTimeout(checkJQuery, 100);
          }
        };
        checkJQuery();
      });
    }
    
    // Bootstrap JS - 依赖 jQuery  
    await loadScript('/app/libs/bootstrap/dist/js/bootstrap.min.js');
    console.log('Bootstrap loaded');
    
    // Select2 - 依赖 jQuery
    await loadScript('/app/libs/select2/dist/js/select2.min.js');
    console.log('Select2 loaded:', typeof window.jQuery.fn.select2 !== 'undefined');
    
    // Angular 核心
    await loadScript('/app/libs/angular/angular.min.js');
    console.log('Angular loaded:', typeof window.angular !== 'undefined');
    
    // Angular 扩展模块
    await loadScript('/app/libs/angular-cookies/angular-cookies.min.js');
    await loadScript('/app/libs/angular-ui-router/release/angular-ui-router.min.js');
    await loadScript('/app/libs/angular-strap/dist/angular-strap.min.js');
    
    // Angular 翻译模块
    await loadScript('/app/libs/angular-translate/dist/angular-translate.min.js');
    await loadScript('/app/libs/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js');
    await loadScript('/app/libs/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js');
    await loadScript('/app/libs/angular-translate-storage-local/angular-translate-storage-local.min.js');
    
    // 其他 Angular 组件
    await loadScript('/app/libs/ng-table/bundles/ng-table.min.js');
    await loadScript('/app/libs/ngstorage/ngStorage.min.js');
    
    console.log('第三方库已全部加载完成');
    
    // 设置标志表示库已加载完成
    window.vendorLibsLoaded = true;
    
    // 触发自定义事件通知应用库已加载完成
    window.dispatchEvent(new CustomEvent('vendorLibsLoaded'));
    
  } catch (error) {
    console.error('加载第三方库时出错:', error);
  }
}

// 立即开始加载
loadVendorLibs();